using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XML;
using System.IO;
using System.Text;

public class LevelEditorManager : MonoBehaviour {

    public List<List<Tile>> tiles = new List<List<Tile>>();
    public GameObject baseTile;
    public Vector3 startPos;
    public string fileName;

    int nbTileX = 13;
    int nbTileY = 7;

	// Use this for initialization
	void Start () {

        CreationMap();
	}

    void CreationMap()
    {
        for (int i = 0; i < nbTileX; ++i)
        {
            List<Tile> tile = new List<Tile>();
            for (int j = 0; j < nbTileY; ++j)
            {
                GameObject newTile = Instantiate(baseTile) as GameObject;
                newTile.transform.position = new Vector3(startPos.x + i * newTile.collider.bounds.size.x, -10, startPos.z + j * newTile.collider.bounds.size.z);
                tile.Add(newTile.GetComponent<Tile>());
                newTile.GetComponent<Tile>().editor = true;
            }

            tiles.Add(tile);
        }
    }
	
	// Update is called once per frame
	void Update () {
        if (Input.GetKeyDown(KeyCode.S))
        {
            Save();
        }
	}

    void Save()
    {
        OutStream stream = new OutStream();

        //Translate in XML format
        stream.Prolog("utf-8")
            .Start("Tiles");
        foreach (List<Tile> list in tiles)
        {
            foreach (Tile tile in list)
            {
                stream.Start("Tile")
                    .Content("Type", tile.type.ToString())
                    .Content("pos", tile.transform.position);
                stream.End();
            }
        }
        stream.End();



        //Save in File
        using (FileStream fs = File.Create("./Assets/Resources/XML/" + fileName + ".xml"))
        {
            AddText(fs, stream.Serialize(true));
        }
    }

    private static void AddText(FileStream fs, string value)
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }

}
